<?php

class mySQL implements Drivers {
	
	private $db;
	private $pass;
	private $user;
	private $server;
	private $link;
	public $storage = array();
	
	function connect($db,$pass,$user,$server){
		
		$this->db 			= $db;
		$this->pass			= $pass;
		$this->user 		= $user;
		$this->server 	= $server;
		$this->link 		= @mysql_connect($server,$user,$pass);
		
		if($this->link === false)
			die('Error establishing database connection.');
		
		$this->db($db);
		
	}
	
	function db($db) {
		$this->db = $db;
		return mysql_select_db($this->db,$this->link);
	}

	function __do_query($sql) {
		return @mysql_unbuffered_query($sql,$this->link);	
	}
	
	function query($name, $string = null){
	
		if(!empty($string)){
			$this->storage[$name]['query'] = $string;
		}

		return $this;
	}

	function fetch($name, $identifier = null, $search = null){
	
		$resource = $this->__do_query($this->storage[$name]['query']);
		
		if(is_bool($resource)){
			return $resource;
		}
		
		$result = array();
		$num = 1;
		
		while($row = mysql_fetch_assoc($resource)){
			$index = 'row'.$num;
			
			if($identifier != null){
				if(!empty($row[$identifier])){
				
					if($search == $row[$identifier]){
						mysql_free_result($resource);
						$this->storage[$name]['result'] = $row;
						return $row;
					}
					
					$index = $row[$identifier];
				}
			}

			$result[$index] = $row;
			$num++;
		}
		
		$this->storage[$name]['result'] = $result;
		return $result;
		
	}
	
	function result($name = null){
		
		if($name == null){
			reset($this->storage);
			$name = key($this->storage);
			return $this->__do_query($this->storage[$name]['query']);
		}
		
		if(isset($this->storage[$name]['result'])){
			return $this->storage[$name]['result'];
		}

	}
	
}

?>